Ext.define('MyApp.controller.navigation.NavigationController', {
	extend : 'MyApp.controller.share.BaseGridController',
	views : ['navigation.NavigationPanel', 'navigation.ToolbarMenuAddForm','authority.AuthorityGirdView','authority.AuthorityForm'],
	stores : ['NavigationStore'],
	models : ['ToolbarMenuEntity','AuthorityEntity','NavigationEntity'],
	requires : ['MyApp.store.GlyphStore'],
	refs : [
			// { ref: 'viewport', selector: 'viewport' },
	{
		ref : 'navigationfrom',
		selector : 'navigationPanel form'
	}, {
		ref:'authoritygrid',
		selector:'authorityview grid'
	},{
		ref:'editAuthoritybtn',
		selector:'authorityview button#editAuthority'
	},{
		ref:'deleteAuthoritybtn',
		selector:'authorityview button#deleteAuthority'
	},{
		ref : 'toolbarMenuAddForm',
		selector : 'toolbarMenuAddForm'
	}, {
		ref : 'navigationtreepanel',
		selector : 'navigationPanel treepanel'
	}, {
		ref : 'toolbarMenuGrid',
		selector : 'navigationPanel grid'
	}, {
		ref : 'authoritymanager',
		selector : 'navigationPanel button#authoritymanager'
	},  {
		ref : 'addRowButton',
		selector : 'navigationPanel button#addrow'
	}, {
		ref : 'addSameButton',
		selector : 'navigationPanel button#addSame'
	}, {
		ref : 'addNextButton',
		selector : 'navigationPanel button#addNext'
	}, {
		ref : 'saveButton',
		selector : 'navigationPanel button#save'
	}, {
		ref : 'deleteButton',
		selector : 'navigationPanel button#delete'
	}],
	init : function() {
		this.control({
			'navigationPanel button#authoritymanager' : {
				click : function(btn) {
					var me = this,
						record = me.getNavigationtreepanel().getSelectionModel().getLastSelected(),
						win = Ext.widget('authorityview', {animateTarget : document.body}),
						grid = win.down('grid');
						win.setTitle('应用' + record.get('text')
									+ ' 对应的用户');
						grid.reconfigure(record.authorities());
						grid.getStore().load({
								    scope: this,
								    params:{
								    	navigationid:record.get('id')
    								},
								    callback: function(records, operation, success) {
								    	//grid.getStore().removeFilter( );
								    }
								}
						);
						win.show();
				}
			},
			'authorityview grid' : {
						select : function() {
							this.onSetButtonStatus(false);
						},
						deselect : function() {
							this.onSetButtonStatus(true);
						}
					},
			'authorityview button#addAuthority':{
				click:function(btn){
					this.onAddButtonClick('authorityform');
				}
			},
			'authorityview button#editAuthority':{
				click:function(btn){
					var record = btn.up('authorityview').down('grid').getSelectionModel().getLastSelected(),
						win = Ext.widget('authorityform', {animateTarget : document.body});
						win.setTitle('修改权限描述');
						win.down('form').getForm().loadRecord(record);
						win.down('form').down('textfield[name=authorityName]').setDisabled( true );
						win.show();
				}
			},
			'authorityview button#deleteAuthority':{
				click:function(btn){
					var me = this;
						Ext.MessageBox.confirm('提示', '确定要删除此记录吗?', function showResult(
									btnResult) {
								if (btnResult == 'yes') {
									var grid=btn.up('authorityview').down('grid'),
										records = grid.getSelectionModel().getSelection( ),
										store = grid.getStore();
										if(records.length>0){
											var arr = new Array();
											for (var i = 0; i < records.length; i++) {
												arr.push(records[i].getData());
											}
											Ext.Ajax.request({
											    url: store.getProxy( ).api.destroy,
											    jsonData: Ext.encode(arr),
											    success: function(response){
											        var text = response.responseText;
											        if(text==1){
														store.remove(records);
														me.onSetButtonStatus(true);
											        	Ext.MessageBoxUtil.msg('提示','删除成功!');
											        }else{
											        	Ext.MessageBoxUtil.msg('提示','删除失败!');
											        }
											    },
									             failure: function (response, options) {
									             	Ext.MessageBoxUtil.msg('提示','操作失败,错误编号：'+ response.status);
									             }
											});
										}
								}
							});
				}
			},
			'authorityform button#save':{
				click:function(btn){
					var me=this,win = btn.up('window'),
						navigation = me.getNavigationtreepanel().getSelectionModel().getLastSelected(),
						store = me.getAuthoritygrid().getStore();
					var form = win.down('form').getForm();
					if (form.isValid()) {
						var record = form.getRecord();
						form.setValues({navigationid:navigation.get('id')});
						if (record) {
							record.beginEdit();
							record.set(form.getValues());
							record.endEdit();
							store.sync({
								success : function(response) {
									var text = Ext.decode(response.operations[0].response.responseText);
									if (text == '0') {
										Ext.MessageBoxUtil.msg('提示', '数据提交失败!');
									} else {
										Ext.MessageBoxUtil.msg('提示', '数据提交成功!');
										win.close();
									}
								}
							});
						}else{
							record = Ext.create(me.getAuthorityEntityModel(), form.getValues());
							store.add(record);
							store.sync({
								success : function(response) {
									var text = Ext.decode(response.operations[0].response.responseText);
									if (text == '0') {
										Ext.MessageBoxUtil.msg('提示', '数据提交失败!');
									} else {
										record.set('id', text.id);
										record.commit();
										Ext.MessageBoxUtil.msg('提示', '数据提交成功!');
										win.close();
									}
								}
							});
						}
					}
				}
			},
			/**
			 * 点击树形节点是加载form表单
			 */
			'navigationPanel treepanel' : {
				selectionchange : function(selModel, records) {
					if (records[0]) {
						this.getNavigationfrom().getForm()
								.loadRecord(records[0]);
						if(records[0].isLeaf()){
							this.getToolbarMenuGrid().reconfigure(records[0].toolbarMenuEntities());
						}else{
							this.getToolbarMenuGrid().reconfigure([]);
						}
					}
				},
				select : this.onSelect,
				load : function(t) {
					if (t.getRootNode().firstChild) {
						t.getRootNode().firstChild.expand();
					}
				},
				deselect : this.onDeselect
			},
			'navigationPanel treepanel > treeview' : {
				drop : function(node, data, overModel, dropPosition) {
					this.getNavigationtreepanel().getSelectionModel()
							.select(data.records[0]);
				}
			},
			'navigationPanel grid' : {
				itemcontextmenu : function(view, rec, node, index, e) {
					e.stopEvent();
					var me = this,
						store = me.getToolbarMenuGrid().getStore();
					Ext.create('Ext.menu.Menu', {
								items : [{
											glyph : 61771,
											text : '修改',
											itemid : 'updateRow',
											handler : function(widget, event) {
													var win = Ext.widget('toolbarMenuAddForm', {animateTarget: document.body});
													win.setTitle('修改按钮信息');
													win.down('form').getForm().loadRecord(rec);
													var navigationRecord = me.getNavigationfrom().getForm().getRecord();
													var authoritycom = win.down('form').down('combobox[name=authorityid]');
													authoritycom.store  = navigationRecord.authorities();
													authoritycom.allQuery = navigationRecord.get('id');
													win.show();
											}
										}, {
											glyph : 0xf1f8,
											text : '删除',
											itemid : 'deleteRow',
											handler : function(widget, event) {
													me.rightMenuDeleteRow(store,rec);
											}
										}]
							}).showAt(e.getXY());
					return false;
				}
			},
			'navigationPanel button#addrow' : {
				click : function(btn) {
					var navigationRecord = this.getNavigationfrom().getForm().getRecord();
					if(navigationRecord.get('id')!=null){
						var win = Ext.widget('toolbarMenuAddForm', {animateTarget : document.body});
						var authoritycom = win.down('form').down('combobox[name=authorityid]');
						authoritycom.store  = navigationRecord.authorities();
						authoritycom.allQuery = navigationRecord.get('id');
						win.show();
					}else{
						Ext.MessageBoxUtil.msg('提示', '请先保存导航信息!');
					}
				}
			},
			'toolbarMenuAddForm button#cancel' : {
				click : function(btn) {
					btn.up('window').close();
				}
			},
			'toolbarMenuAddForm button#save' : {
				click : 'winFormSaveButton'
			},
			'navigationPanel button#addSame' : {
				click : function(btn) {
					this.addNode('same');
				}
			},
			'navigationPanel button#addNext' : {
				click : function(btn) {
					this.addNode('next');
				}
			},
			'navigationPanel button#delete' : {
				click : 'ondeletebuttonClick'
			},
			'navigationPanel button#save' : {
				click : 'onsavebuttonClick'
			}
		});
	},
	onSetButtonStatus:function(st){
		this.getEditAuthoritybtn().setDisabled(st);
		this.getDeleteAuthoritybtn().setDisabled(st);
	},
	winFormSaveButton:function(btn) {
					var me = this;
					var win = btn.up('window');
					var form = win.down('form').getForm();
					if (form.isValid()) {
						var record = form.getRecord();
						if (record) {
							record.beginEdit();
							record.set(form.getValues());
							record.endEdit();
							record.save({
								success : function(response) {
									if (response) {
										record.commit();
										Ext.MessageBoxUtil.msg('提示', '数据提交成功!');
										win.close();
									} else {
										Ext.MessageBoxUtil.msg('提示', '数据提交失败!');
									}
								}
							});
						} else {
							record = Ext.create(me.getToolbarMenuEntityModel(),
									form.getValues());
							record.setDirty();
							record.set('navigationid',this.getNavigationfrom().getForm().getRecord().get('id'));
							record.save({
								success : function(response) {
									if (response) {
										me.getToolbarMenuGrid().getStore()
												.add(response);
										Ext.MessageBoxUtil.msg('提示', '数据提交成功!');
										win.close();
									} else {
										Ext.MessageBoxUtil.msg('提示', '数据提交失败!');
									}
								}
							});
						}
					}
	},
	rightMenuDeleteRow : function(store, rec) {
		 Ext.MessageBox.confirm('提示', '确定要删除此记录吗?', function showResult(btnResult){
		 	if(btnResult=='yes'){
		 		store.remove(rec);
				rec.destroy({
							success : function(response) {
								if (response) {
									Ext.MessageBoxUtil.msg('提示', '操作成功!');
								} else {
									Ext.MessageBoxUtil.msg('提示', '操作失败!');
								}
							}
						});
		 	}
		 });
	},
	onsavebuttonClick : function(btn) {
		var form = this.getNavigationfrom().getForm();
		if (form.isValid()) {
			record = form.getRecord();
			if (record) {
				record.beginEdit();
				record.set(form.getValues());
				record.endEdit();
				this.getNavigationtreepanel().getStore().sync({
					success : function(response) {
						var text = Ext
								.decode(response.operations[0].response.responseText);
						if (text == 0) {
							Ext.MessageBoxUtil.msg('提示', '操作失败,请重试!');
						} else {
							if (record.get('id') == null) {
								record.set('id', text.id);
							}
							Ext.MessageBoxUtil.msg('提示', '操作成功!');
						}
					},
					failure : function(response, options) {
						Ext.MessageBoxUtil.msg('提示', '操作失败,错误编号：'
										+ response.status);
					}
				});
			}
		} else {
			Ext.MessageBoxUtil.msg('提示', '表单中有为填写的信息,请填写完整');
		}
	},
	ondeletebuttonClick : function(btn) {
		var me = this;
		var record = me.getNavigationtreepanel().getSelectionModel()
				.getLastSelected();
		if (record.childNodes.length > 0) {
			Ext.MessageBox.alert('提示', '此记录包括子记录,需先删除子记录!');
		} else {
			Ext.MessageBox.confirm('提示', '确定要删除此记录吗?', function showResult(
					btnResult) {
				if (btnResult == 'yes') {
					var parentNode = record.parentNode;
					if (parentNode.childNodes.length == 1) {
						parentNode.set('leaf', true);
					}
					record.remove();
					me.getNavigationtreepanel().getStore().sync({
						success : function(response) {
							var text = Ext
									.decode(response.operations[0].response.responseText);
							if (text == 1) {
								me.getNavigationfrom().getForm().reset();
								me.onDeselect();
								Ext.MessageBoxUtil.msg('提示', '操作成功!');
							} else {
								Ext.MessageBoxUtil.msg('提示', '操作失败!');
							}
						},
						failure : function(response, options) {
							Ext.MessageBoxUtil.msg('提示', '操作失败,错误编号：'
											+ response.status);
						}
					});
				}
			});
		}
	},
	addNode : function(param) {
		var selModel = this.getNavigationtreepanel().getSelectionModel(), parentNode = null;
		if ('next' == param) {
			parentNode = selModel.getLastSelected();
		} else {
			var selectNode = selModel.getLastSelected();
			parentNode = selectNode.parentNode;
		}
		newNode = Ext.create('MyApp.model.NavigationEntity', {
			text : 'New ',
			leaf : true,
			parentId : parentNode.get('id'),
			loaded : true
				// set loaded to true,
			});
		parentNode.appendChild(newNode);
		if (parentNode.isLeaf()) {
			parentNode.set('leaf', false);
		}
		if (!parentNode.isExpanded()) {
			parentNode.expand();
		}
		selModel.select(newNode);
	},
	onSelect : function() {
		this.setButtonsDisabled(false);
	},
	onDeselect : function() {
		this.setButtonsDisabled(true);
	},

	setButtonsDisabled : function(e) {
		this.getAuthoritymanager().setDisabled(e);
		this.getSaveButton().setDisabled(e);
		this.getDeleteButton().setDisabled(e);
		this.getAddNextButton().setDisabled(e);
		this.getAddSameButton().setDisabled(e);
		this.getNavigationfrom().setDisabled(e);
		this.getAddRowButton().setDisabled(e);
	}
});